package com.designpattern.flyweight;


import java.util.HashMap;
import java.util.Map;

//享元模式
public class FlyWeightTest {
    public static void main(String[] args) {

        TreeFactory treeFactory = new TreeFactory();
        TreeNode treeNode1 = new TreeNode(3, 1, TreeFactory.getTree("xxx", "yyy"));
        TreeNode treeNode2 = new TreeNode(1, 2, TreeFactory.getTree("xxx", "yyy2"));
        TreeNode treeNode3 = new TreeNode(3, 1, TreeFactory.getTree("xxx1", "yyy"));
        TreeNode treeNode4 = new TreeNode(3, 1, TreeFactory.getTree("xxx3", "yyy"));

    }
}

class TreeFactory{
    private static Map<String, Tree> map = new HashMap<>();
    public static Tree getTree(String name,String data){
        if (map.containsKey(name)) {
            return map.get(name);
        }
        Tree tree = new Tree(name,data);
        map.put(name, tree);
        return tree;
    }
}
class TreeNode{
    private final int x;
    private final int y;

    private Tree tree;

    public TreeNode(int x, int y, Tree tree) {
        this.x = x;
        this.y = y;
        this.tree = tree;
    }

    public int getX() {
        return x;
    }


    public int getY() {
        return y;
    }
    public Tree getTree() {
        return tree;
    }
    public void setTree(Tree tree) {
        this.tree = tree;
    }
}
class Tree{
    public Tree(String name, String data) {
        System.out.println("name:" + name + ",data:" + data);
        this.name = name;
        this.data = data;
    }

    private String name;
    private String data;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
